<template>
	<view class="my-page">
		<u-navbar leftIconColor="#ffffff" :autoBack="true" :placeholder="true" bgColor="rgba(255,255,255,0.0)">
			<view slot="center" class="nav-title">
				订单详情
			</view>
		</u-navbar>
		<view class="head" v-if="info.purchase">
			<view class="head-left" v-if="info.purchase.status == 1">
				<view class="head-title">
					请上传支付凭证
				</view>
				<view class="head-time">
					<view>请在 </view>
					<view class="count" v-if="info.userInfo">
						<u-count-down :time="info.userInfo.deal_time * 1000" @change="onChange" format="HH:mm:ss"
							autoStart millisecond>
							<view class="time">
								<view class="time__custom">
									<text
										class="time__custom__item">{{ timeData.hours>10?timeData.hours:timeData.hours}}</text>
								</view>
								<text class="time__doc">:</text>
								<view class="time__custom">
									<text class="time__custom__item">{{ timeData.minutes }}</text>
								</view>
								<text class="time__doc">:</text>
								<view class="time__custom">
									<text class="time__custom__item">{{ timeData.seconds }}</text>
								</view>
							</view>
						</u-count-down>
					</view>
					<view>内付款</view>
				</view>
			</view>
			<view class="head-left" v-if="info.purchase.status == 2">
				<view class="head-title">
					等待确认
				</view>
				<view class="head-time">
					<view>剩余时间</view>
					<view class="count" v-if="info.userInfo">
						<u-count-down :time="info.userInfo.deal_time * 1000" @change="onChange" format="HH:mm:ss"
							autoStart millisecond>
							<view class="time">
								<view class="time__custom">
									<text
										class="time__custom__item">{{ timeData.hours>10?timeData.hours:timeData.hours}}</text>
								</view>
								<text class="time__doc">:</text>
								<view class="time__custom">
									<text class="time__custom__item">{{ timeData.minutes }}</text>
								</view>
								<text class="time__doc">:</text>
								<view class="time__custom">
									<text class="time__custom__item">{{ timeData.seconds }}</text>
								</view>
							</view>
						</u-count-down>
					</view>
				</view>
			</view>
			<view class="head-left" v-if="info.purchase.status == 3">
				<view class="head-title">
					已完成
				</view>
			</view>
		</view>
		<view class="item" v-if="info.purchase">
			<view class="item-top">
				<image class="logo" :src="info.purchase.logo" mode=""></image>
				<view class="item-right">
					<view class="item-title">
						{{info.purchase.name}}
					</view>
					<view class="item-cont">
						<view class="info-item">
							<view class="info-text">
								利润(CNY)
							</view>
							<view class="info-num">
								{{info.purchase.reward}}
							</view>
						</view>
						<view class="info-item">
							<view class="info-text">
								收益率/日
							</view>
							<view class="info-num">
								{{info.purchase.rate}}
							</view>
						</view>
						<view class="info-item">
							<view class="info-text">
								价值
							</view>
							<view class="info-num info-title">
								{{info.purchase.price}}
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="tabs" v-if="info.receive">
			<view v-if="info.receive[1]" :class="current == 0?'active-item': 'tabs-item'" class="tabs-item"
				@click="cutTabs(0)">
				<view class="tabs-text">
					支付宝
				</view>
			</view>
			<view v-if="info.receive[2]" :class="current ==1?'active-item': 'tabs-item'" class="tabs-item"
				@click="cutTabs(1)">
				<view class="tabs-text">
					微信
				</view>
			</view>
			<view v-if="info.receive[3]" :class="current == 2?'active-item': 'tabs-item'" class="tabs-item"
				@click="cutTabs(2)">
				<view class="tabs-text">
					银行卡
				</view>
			</view>
		</view>
		<view class="content" v-if="current == 0 && info.receive && info.receive[1]">
			<view class="info-item">
				<view>
					支付宝账号
				</view>
				<view class="item-right">
					{{info.receive[1].account_num}}
					<image @click="gocory(info.receive[1].account_num)" src="/static/home/copy.png" mode="heightFix">
					</image>
				</view>
			</view>
			<view class="info-item">
				<view>
					支付宝昵称
				</view>
				<view class="item-right">
					{{info.receive[1].name}}
					<image @click="gocory(info.receive[1].name)" src="/static/home/copy.png" mode="heightFix"></image>
				</view>
			</view>
			<view class="code">
				<image @click="goeve(info.receive[1].receive_qrcode)" :src="info.receive[1].receive_qrcode"
					mode="widthFix">
				</image>
			</view>
			<view class="btn">
				<u-button style="color: #000;"  size="large" v-if="info.purchase.status == 1"
					color="linear-gradient(255.89deg, #FFF0E3 6.94%, #D7B39A 87.16%)" shape="circle" type="primary"
					text="上传支付凭证" @click="show = true"></u-button>
				<u-button style="color: #000;"  size="large" v-if="info.purchase.status == 2"
					color="linear-gradient(255.89deg, #FFF0E3 6.94%, #D7B39A 87.16%)" shape="circle" type="primary"
					text="等待对方确定"></u-button>
			</view>
			<view class="tips">
				温馨提醒:付款时请不要备注任何信息，推荐只用支付宝，银行卡号转账,如果联系不上对方可以联系线上客服解决!
			</view>
		</view>
		<view class="content" v-if="current == 1 && info.receive&& info.receive[2]">
			<view class="info-item">
				<view>
					微信账号
				</view>
				<view class="item-right">
					{{info.receive[2].account_num}}
					<image @click="gocory(info.receive[2].account_num)" src="../../../static/home/copy.png"
						mode="heightFix">
					</image>
				</view>
			</view>
			<view class="info-item">
				<view>
					微信昵称
				</view>
				<view class="item-right">
					{{info.receive[2].name}}
					<image @click="gocory(info.receive[2].name)" src="../../../static/home/copy.png" mode="heightFix">
					</image>
				</view>
			</view>
			<view class="code">
				<image @click="goeve(info.receive[2].receive_qrcode)" :src="info.receive[2].receive_qrcode"
					mode="widthFix"></image>
			</view>
			<view class="btn">
				<u-button style="color: #000;"  size="large" v-if="info.purchase.status == 1"
					color="linear-gradient(255.89deg, #FFF0E3 6.94%, #D7B39A 87.16%)" shape="circle" type="primary"
					text="上传支付凭证" @click="show = true"></u-button>
				<u-button style="color: #000;"  size="large" v-if="info.purchase.status == 2"
					color="linear-gradient(255.89deg, #FFF0E3 6.94%, #D7B39A 87.16%)" shape="circle" type="primary"
					text="等待对方确定"></u-button>
			</view>
			<view class="tips">
				提示:付款时请不要备注任何信息，推荐只用支付宝，银行卡号转账,如果联系不上对方可以联系线上客服解决!
			</view>

		</view>
		<view class="content" v-if="current == 2  && info.receive && info.receive[3]">
			<view class="info-item">
				<view>
					银行名称
				</view>
				<view class="item-right">
					{{info.receive[3].account_num}}
					<image @click="gocory(info.receive[3].account_num)" src="../../../static/home/copy.png"
						mode="heightFix">
					</image>
				</view>
			</view>
			<view class="info-item">
				<view>
					银行卡号
				</view>
				<view class="item-right">
					{{info.receive[3].bank_num}}
					<image @click="gocory(info.receive[3].bank_num)" src="../../../static/home/copy.png"
						mode="heightFix">
					</image>
				</view>
			</view>
			<view class="info-item">
				<view>
					收款人名
				</view>
				<view class="item-right">
					{{info.receive[3].name}}
					<image @click="gocory(info.receive[3].name)" src="../../../static/home/copy.png" mode="heightFix">
					</image>
				</view>
			</view>
			<view class="btn">
				<u-button style="#000"  size="large" v-if="info.purchase.status == 1" color="linear-gradient(255.89deg, #FFF0E3 6.94%, #D7B39A 87.16%)" shape="circle" type="primary" text="上传支付凭证"
					@click="show = true"></u-button>
				<u-button style="#000"  size="large" v-if="info.purchase.status == 2" color="linear-gradient(255.89deg, #FFF0E3 6.94%, #D7B39A 87.16%)" shape="circle" type="primary"
					text="等待对方确定"></u-button>
			</view>
			<view class="tips">
				提示:付款时请不要备注任何信息，推荐只用支付宝，银行卡号转账,如果联系不上对方可以联系线上客服解决!
			</view>
		</view>
		<view class="content" v-if="info.userInfo">
			<view class="tell-item">
				<view>收款方</view>
				<view class="tell-right" @click="gotell(info.userInfo.tel)">
					<view>{{info.userInfo.tel||'无'}}</view>
					<image src="../../../static/home/tell.png" mode="heightFix"></image>
				</view>
			</view>
			<view class="tell-item none-item">
				<view>紧急联系人</view>
				<view class="tell-right" @click="gotell(info.userInfo.urgent_tel)">
					<view>{{info.userInfo.urgent_tel||'无' }}</view>
					<image src="../../../static/home/tell.png" mode="heightFix"></image>
				</view>
			</view>
		</view>
		<u-popup :show="show" @close="close" mode="center" round="20rpx">
			<view class="pop">
				<view class="pop-title">
					上传凭证
				</view>
				<view class="up">
					<image v-if="img == ''" @click="upLoadImg" src="/static/home/up-voucher.png" mode=""></image>
					<image v-else :src="img" @click="upLoadImg" mode=""></image>
				</view>
				<view class="btn">
					<view class="btn-item" @click="close">
						取消
					</view>
					<view class="btn-item next-btn" @click="gobuy">
						确认
					</view>
				</view>
			</view>
		</u-popup>
		<compress ref="compress" />
	</view>
</template>

<script>
	import compress from '@/components/MarsXHChang-CavansCompressImg/compress.vue'
	export default {
		components: {
			compress
		},
		data() {
			return {
				current: 0,
				show: false,
				info: {},
				id: '',
				timeData: {},
				img: ''
			}
		},
		onLoad(e) {
			this.id = e.id
			this.uploadVoucherIndex()
		},
		methods: {
			gobuy() {
				if (this.img == '') {
					uni.showToast({
						title: '请上传支付凭证！',
						icon: 'none'
					})
					return
				}
				uni.showLoading({
					mask: true
				})
				let params = {
					id: this.id,
					voucher: this.img
				}
				this.$Request({
					method: 'POST',
					url: '/api/trade/uploadVoucher',
					data: params,
					ismsg: true,
				}).then(res => {
					if (res.code == 1) {
						uni.hideLoading()
						this.show = false
						this.uploadVoucherIndex()
					}
				})

			},
			async upLoadImg() {
				try {
					// 1. 选择图片
					let {
						tempFilePaths
					} = await this.chooseImage();
					let filePath = tempFilePaths[0];

					uni.showLoading({
						title: '上传中...',
						mask: true
					});

					// 2. 压缩图片
					let compressParams = {
						src: filePath // 必选：要压缩的图片地址
					};

					// 等待压缩完成
					const compressedImg = await this.$refs.compress.compress(compressParams);

					// 3. 获取OSS签名
					const signData = await this.getOssSign();
					console.log(signData)
					const fileName = this.generateFileName(compressedImg); // 需要实现这个方法
					const key = `${signData.dir}${fileName}`;

					// 5. 上传到OSS
					const fileUrl = await this.uploadToOSS(compressedImg, key, signData);

					uni.showToast({
						title: '上传成功',
						icon: 'success'
					});

					this.img = fileUrl; // 返回文件URL供外部使用
				} catch (error) {
					console.error('上传失败:', error);
					uni.showToast({
						title: error.message || '上传失败',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			},
			// 生成文件名方法（如果还没有）
			generateFileName(filePath) {
				// 获取干净的文件名（不含路径）
				const filename = filePath.split('/').pop(); // 获取最后一部分

				// 提取纯净的扩展名（去掉查询参数等）
				let extension = 'jpg'; // 默认值
				const match = filename.match(/\.([a-z0-9]+)(?:\?|$)/i);
				if (match) {
					extension = match[1].toLowerCase();
				}

				// 生成格式化的日期时间字符串
				const now = new Date();
				const year = now.getFullYear();
				const month = String(now.getMonth() + 1).padStart(2, '0');
				const day = String(now.getDate()).padStart(2, '0');
				const hours = String(now.getHours()).padStart(2, '0');
				const minutes = String(now.getMinutes()).padStart(2, '0');
				const seconds = String(now.getSeconds()).padStart(2, '0');
				const milliseconds = String(now.getMilliseconds()).padStart(3, '0');

				// 添加随机字符串确保唯一性
				const randomStr = Math.random().toString(36).substring(2, 6);

				// 组合成文件名：YYYYMMDD_HHMMSSmmm_xxxx.扩展名
				return `${year}${month}${day}_${hours}${minutes}${seconds}${milliseconds}_${randomStr}.${extension}`;
			},
			// 封装选择图片方法
			chooseImage() {
				return new Promise((resolve, reject) => {
					uni.chooseImage({
						count: 1,
						sizeType: ['compressed'], // 尝试压缩
						sourceType: ['album'],
						success: resolve,
						fail: (err) => {
							console.error('选择图片失败:', err);
							reject(new Error('选择图片失败，请重试'));
						}
					});
				});
			},

			// 获取OSS签名方法
			async getOssSign() {
				try {
					let res = await this.$Request({
						method: 'GET',
						url: '/api/upload/ossSign',
						data: {},
						ismsg: false
					});

					if (res.code === 1) {
						return res;
					} else {
						throw new Error(res.msg || '获取上传凭证失败');
					}
				} catch (error) {
					console.error('获取OSS签名失败:', error);
					throw new Error('获取上传凭证失败，请检查网络');
				}
			},


			uploadToOSS(filePath, key, signData) {
				return new Promise((resolve, reject) => {
					const uploadTask = uni.uploadFile({
						url: signData.host, // 确保host不带结尾斜杠
						filePath: filePath,
						name: 'file',
						formData: {
							key: key,
							policy: signData.policy,
							OSSAccessKeyId: signData.accessid,
							success_action_status: '200',
							signature: signData.signature
						},
						success: (res) => {
							if (res.statusCode === 200) {
								// 正确拼接URL方式：
								const host = signData.host.replace(/\/+$/, ''); // 移除host末尾的斜杠
								const cleanKey = key.replace(/^\/+/, ''); // 移除key开头的斜杠
								console.log(`${host}/${cleanKey}`)
								resolve(`${host}/${cleanKey}`); // 单斜杠连接

							} else {
								reject(new Error(`上传失败，状态码: ${res.statusCode}`));
							}
						},
						fail: (err) => {
							reject(new Error('文件上传失败，请检查网络连接'));
						}
					});
				});
			},

			goeve(img) {
				let arr = []
				arr.push(img)
				uni.previewImage({
					urls: arr
				})
			},
			gocory(info) {
				uni.setClipboardData({
					data: info,
					success() {
						uni.showToast({
							title: '复制成功！',
							icon: 'none'
						})
					},
					fail() {
						uni.showToast({
							title: '复制失败！',
							icon: 'none'
						})
					}
				})
			},
			gotell(tell) {
				if (!tell) {
					uni.showToast({
						title: '手机号为空！',
						icon: 'none'
					})
					return
				}
				uni.makePhoneCall({
					phoneNumber: tell
				})
			},
			onChange(e) {
				this.timeData = e
			},
			uploadVoucherIndex() {
				let params = {
					id: this.id
				}
				this.$Request({
					method: 'POST',
					url: '/api/trade/uploadVoucherIndex',
					data: params,
					ismsg: false,
				}).then(res => {
					if (res.code == 1) {
						this.info = res.data
						if (this.info.receive[1]) {
							this.current = 0
						} else if (this.info.receive[2]) {
							this.current = 1
						} else if (this.info.receive[3]) {
							this.current = 2
						}
					}
				})

			},
			cutTabs(index) {
				this.current = index
			},
			close() {
				this.show = false
			}
		}
	}
</script>
<style>
	page {
		background: #000000;
	}
</style>
<style lang="scss" scoped>
	.my-page {
		min-height: 100vh;
		position: relative;
		background-image: url('../../../static/login/login-bg.png');
		background-repeat: no-repeat;
		background-size: 100% 593px;
		padding: 30rpx;

		.nav-title {
			color: #ffffff;
		}

		.pop {
			width: 650rpx;
			padding: 30rpx;

			.pop-title {
				text-align: center;
				font-size: 32rpx;
				color: #333;
			}

			.up {
				padding: 40rpx;
				text-align: center;

				image {
					width: 300rpx;
					height: 300rpx;
				}
			}

			.btn {
				display: flex;
				justify-content: space-around;

				.btn-item {
					width: 35%;
					text-align: center;
					padding: 20rpx;
					border-radius: 40rpx;
					background: #999;
					color: #fff;
					font-size: 32rpx;
				}

				.next-btn {
					background: #090B08;
					color: #fff;
				}
			}

		}

		.head {
			padding: 0 30rpx;
			margin-top: 30rpx;

			.head-left {
				color: #666;

				.head-title {
					color: #ffffff;
					font-size: 42rpx;
					font-weight: 900;
					text-align: center;
				}

				.head-time {
					display: flex;
					align-items: center;
					justify-content: center;
					font-size: 26rpx;
					margin-top: 20rpx;

					.count {
						padding: 0 5rpx;

						.time {
							@include flex;
							align-items: center;

							&__custom {
								width: 22px;
								height: 22px;
								border-radius: 4px;
								/* #ifndef APP-NVUE */
								display: flex;
								/* #endif */
								justify-content: center;
								align-items: center;

								&__item {
									color: #52ECFA;
									font-size: 14px;
									text-align: center;
								}
							}

							&__doc {
								color: #52ECFA;
							}

							&__item {
								color: #52ECFA;
								font-size: 16px;
								margin-right: 4px;
							}
						}
					}
				}
			}

			image {
				width: 200rpx;
				height: 200rpx;
			}
		}

		.item {
			margin-top: 30rpx;
			padding: 30rpx;
			border-radius: 30rpx;
			background: #1A1A1B;
			position: relative;

			.item-top {
				display: flex;
				align-items: center;
				justify-content: space-between;

				.logo {
					width: 130rpx;
					height: 130rpx;
					border-radius: 10rpx;
				}

				.item-right {
					width: 75%;

					.item-title {
						font-size: 32rpx;
						color: #ffffff;
					}

					.item-cont {
						display: flex;
						justify-content: space-between;
						text-align: center;
						margin-top: 10rpx;

						.info-item {
							font-size: 28rpx;

							.info-num {
								color: #ffffff;
								font-size: 32rpx;
								font-weight: bold;
								margin-top: 5rpx;
							}

							.info-text {
								color: #999;
								font-size: 24rpx;
								margin-top: 5rpx;
							}

							.info-title {
								color: #52ECFA;
								font-size: 32rpx;
							}
						}
					}
				}
			}

		}

		.tabs {
			display: flex;
			align-items: center;
			margin-top: 30rpx;
			width: 100%;
			background-color: #40404080;
			border-radius: 20rpx;
			padding: 15rpx;

			.tabs-item {
				width: 30.5%;
				font-size: 26rpx;
				font-weight: 500;
				color: #8F8F8F;
				text-align: center;
				padding: 15rpx 0;

				.tabs-text {
					font-size: 28rpx;
					margin-left: 10rpx;
					white-space: nowrap;
					/* 防止文字换行 */
					overflow: hidden;
					text-overflow: ellipsis;
					/* 文字过长显示省略号 */
				}
			}

			.active-item {
				background-color: #FFFFFF;
				border-radius: 10rpx;
				color: #000000;
			}
		}

		.content {
			padding: 30rpx;
			margin-top: 30rpx;

			.info-item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				font-size: 26rpx;
				color: #666;
				margin-bottom: 20rpx;

				.item-right {
					display: flex;
					align-items: center;
					color: #ffffff;
				}

				image {
					width: 24px;
					height: 12px;
					margin-left: 10rpx;
				}
			}

			.code {
				text-align: center;
				padding: 20rpx 0;
				margin-top: 60rpx;

				image {
					width: 300rpx;
					height: 300rpx;
				}
			}

			.tips {
				font-size: 24rpx;
				color: #FFD7A2;
				padding-top: 20rpx;
			}

			.btn {
				margin-top: 40rpx;
			}

			.tell-item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding-bottom: 20rpx;
				margin-bottom: 20rpx;
				font-size: 26rpx;
				color: #666;

				.tell-right {
					display: flex;
					align-items: center;
					color: #ffffff;

					image {
						width: 32rpx;
						height: 32rpx;
						margin-left: 20rpx;
					}
				}
			}

			.none-item {
				padding: 0;
				border: none;
				margin: 0;
			}
		}
	}
</style>